/**
 * ECharts 配置工具类
 * 提供各种图表的配置选项和工具函数
 */

// 优化的颜色配置
export const defaultColors = [
    '#4ade80', '#22d3ee', '#fbbf24', '#f87171', '#a78bfa',
    '#34d399', '#60a5fa', '#fb7185', '#fcd34d', '#c084fc',
    '#10b981', '#06b6d4', '#f59e0b', '#ef4444', '#8b5cf6',
    '#14b8a6', '#3b82f6', '#f97316', '#ec4899', '#84cc16'
];

// 渐变色配置
export const gradientColors = {
    blue: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
            { offset: 0, color: 'rgba(5, 195, 249, 0.8)' },
            { offset: 1, color: 'rgba(5, 195, 249, 0.1)' }
        ]
    },
    green: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
            { offset: 0, color: 'rgba(34, 197, 94, 0.8)' },
            { offset: 1, color: 'rgba(34, 197, 94, 0.1)' }
        ]
    },
    orange: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
            { offset: 0, color: 'rgba(245, 158, 11, 0.8)' },
            { offset: 1, color: 'rgba(245, 158, 11, 0.1)' }
        ]
    }
};

// 获取响应式配置
export const getResponsiveConfig = () => {
    const width = window.innerWidth;
    const height = window.innerHeight;

    if (width <= 480) {
        return {
            fontSize: 10,
            titleFontSize: 12,
            legendItemWidth: 12,
            legendItemHeight: 8,
            gridLeft: '5%',
            gridRight: '5%',
            gridTop: '12%',
            gridBottom: '20%',
            symbolSize: 4,
            lineWidth: 2
        };
    } else if (width <= 768) {
        return {
            fontSize: 11,
            titleFontSize: 13,
            legendItemWidth: 15,
            legendItemHeight: 10,
            gridLeft: '6%',
            gridRight: '6%',
            gridTop: '12%',
            gridBottom: '18%',
            symbolSize: 5,
            lineWidth: 2.5
        };
    } else if (width <= 1024) {
        return {
            fontSize: 12,
            titleFontSize: 14,
            legendItemWidth: 18,
            legendItemHeight: 12,
            gridLeft: '8%',
            gridRight: '8%',
            gridTop: '12%',
            gridBottom: '15%',
            symbolSize: 6,
            lineWidth: 3
        };
    } else if (width <= 1440) {
        return {
            fontSize: 13,
            titleFontSize: 15,
            legendItemWidth: 22,
            legendItemHeight: 14,
            gridLeft: '8%',
            gridRight: '8%',
            gridTop: '10%',
            gridBottom: '12%',
            symbolSize: 7,
            lineWidth: 3
        };
    } else {
        return {
            fontSize: 14,
            titleFontSize: 16,
            legendItemWidth: 25,
            legendItemHeight: 16,
            gridLeft: '8%',
            gridRight: '8%',
            gridTop: '8%',
            gridBottom: '10%',
            symbolSize: 8,
            lineWidth: 3.5
        };
    }
};

// 通用tooltip配置
export const getTooltipConfig = (formatter) => {
    const config = getResponsiveConfig();
    return {
        trigger: 'axis',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(5, 195, 249, 0.5)',
        borderWidth: 1,
        borderRadius: 6,
        padding: [8, 12],
        textStyle: {
            color: '#ffffff',
            fontSize: config.fontSize,
            fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
            fontWeight: '500'
        },
        formatter: formatter || function (params) {
            let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
            params.forEach(param => {
                result += `<div style="margin: 2px 0;">
                    <span style="display: inline-block; width: 10px; height: 10px; background: ${param.color}; border-radius: 50%; margin-right: 8px;"></span>
                    ${param.seriesName}: <span style="font-weight: bold; color: ${param.color};">${param.value}</span>
                </div>`;
            });
            return result;
        }
    };
};

// 通用legend配置
export const getLegendConfig = (position = 'top') => {
    const config = getResponsiveConfig();
    const baseConfig = {
        textStyle: {
            color: '#ffffff',
            fontSize: config.fontSize,
            fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
            fontWeight: '500'
        },
        itemWidth: config.legendItemWidth,
        itemHeight: config.legendItemHeight,
        itemGap: 15
    };

    switch (position) {
        case 'top':
            return { ...baseConfig, top: '5%', left: 'center' };
        case 'bottom':
            return { ...baseConfig, bottom: '5%', left: 'center' };
        case 'left':
            return { ...baseConfig, left: '5%', top: 'center', orient: 'vertical' };
        case 'right':
            return { ...baseConfig, right: '5%', top: 'center', orient: 'vertical' };
        default:
            return { ...baseConfig, top: '5%', left: 'center' };
    }
};

// 通用grid配置
export const getGridConfig = (customConfig = {}) => {
    const config = getResponsiveConfig();
    return {
        left: customConfig.left || config.gridLeft,
        right: customConfig.right || config.gridRight,
        top: customConfig.top || config.gridTop,
        bottom: customConfig.bottom || config.gridBottom,
        containLabel: true
    };
};

// 通用坐标轴配置
export const getAxisConfig = (type = 'category', customConfig = {}) => {
    const config = getResponsiveConfig();
    const baseConfig = {
        axisLine: {
            show: true,
            lineStyle: {
                color: 'rgba(255, 255, 255, 0.3)',
                width: 1
            }
        },
        axisTick: {
            show: true,
            lineStyle: {
                color: 'rgba(255, 255, 255, 0.3)',
                width: 1
            }
        },
        axisLabel: {
            color: 'rgba(255, 255, 255, 0.9)',
            fontSize: config.fontSize,
            fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
            fontWeight: '500',
            margin: 10
        },
        splitLine: {
            show: true,
            lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
                width: 1,
                type: 'dashed'
            }
        }
    };

    if (type === 'value') {
        baseConfig.axisPointer = {
            type: 'line',
            lineStyle: {
                color: 'rgba(5, 195, 249, 0.8)',
                width: 1,
                type: 'dashed'
            }
        };
    }

    return { ...baseConfig, ...customConfig };
};

// 柱状图配置
export const getBarChartOption = (data, customOption = {}) => {
    const config = getResponsiveConfig();

    const defaultOption = {
        color: defaultColors,
        tooltip: getTooltipConfig(),
        legend: getLegendConfig(),
        grid: getGridConfig(),
        xAxis: getAxisConfig('category', {
            data: data.categories || []
        }),
        yAxis: getAxisConfig('value'),
        series: (data.series || []).map((item, index) => ({
            name: item.name,
            type: 'bar',
            data: item.data,
            barWidth: '65%',
            itemStyle: {
                borderRadius: [6, 6, 0, 0],
                opacity: 0.9
            },
            emphasis: {
                itemStyle: {
                    opacity: 1,
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }
            },
            animationDelay: index * 150,
            animationDuration: 1000,
            animationEasing: 'cubicOut'
        }))
    };

    return { ...defaultOption, ...customOption };
};

// 折线图配置
export const getLineChartOption = (data, customOption = {}) => {
    const config = getResponsiveConfig();

    const defaultOption = {
        color: defaultColors,
        tooltip: getTooltipConfig(),
        legend: getLegendConfig(),
        grid: getGridConfig(),
        xAxis: getAxisConfig('category', {
            data: data.categories || [],
            boundaryGap: false
        }),
        yAxis: getAxisConfig('value'),
        series: (data.series || []).map((item, index) => ({
            name: item.name,
            type: 'line',
            data: item.data,
            smooth: 0.4,
            symbol: 'circle',
            symbolSize: config.symbolSize,
            lineStyle: {
                width: config.lineWidth,
                cap: 'round'
            },
            itemStyle: {
                borderWidth: 2,
                borderColor: '#ffffff'
            },
            areaStyle: item.areaStyle !== false ? {
                opacity: 0.2
            } : undefined,
            emphasis: {
                scale: true,
                itemStyle: {
                    borderWidth: 3
                },
                lineStyle: {
                    width: config.lineWidth + 1
                }
            },
            animationDelay: index * 150,
            animationDuration: 1200,
            animationEasing: 'cubicOut'
        }))
    };

    return { ...defaultOption, ...customOption };
};

// 饼图配置
export const getPieChartOption = (data, customOption = {}) => {
    const config = getResponsiveConfig();

    const defaultOption = {
        color: defaultColors,
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: 'rgba(5, 195, 249, 0.5)',
            borderWidth: 1,
            borderRadius: 6,
            padding: [8, 12],
            textStyle: {
                color: '#ffffff',
                fontSize: config.fontSize,
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
                fontWeight: '500'
            },
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: getLegendConfig(),
        series: [{
            name: data.name || '数据',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            data: data.data || [],
            emphasis: {
                itemStyle: {
                    scale: 1.1
                },
                label: {
                    show: true,
                    fontSize: config.fontSize + 2,
                    fontWeight: 'bold'
                }
            },
            itemStyle: {
                borderRadius: 10,
                borderColor: '#ffffff',
                borderWidth: 2
            },
            label: {
                show: true,
                position: 'outside',
                fontSize: config.fontSize + 2,
                color: '#ffffff',
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
                fontWeight: '600',
                formatter: '{b}: {d}%',
                textBorderColor: 'rgba(0, 0, 0, 0.8)',
                textBorderWidth: 2,
                textShadowColor: 'rgba(0, 0, 0, 0.5)',
                textShadowBlur: 3,
                textShadowOffsetX: 1,
                textShadowOffsetY: 1
            },
            labelLine: {
                show: true,
                length: 15,
                length2: 10,
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.8)',
                    width: 2
                }
            },
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
                return Math.random() * 200;
            }
        }]
    };

    return { ...defaultOption, ...customOption };
};

// 地图配置
export const getMapChartOption = (mapName, data, customOption = {}) => {
    const config = getResponsiveConfig();

    const defaultOption = {
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: 'rgba(5, 195, 249, 0.5)',
            borderWidth: 1,
            borderRadius: 6,
            padding: [8, 12],
            textStyle: {
                color: '#ffffff',
                fontSize: config.fontSize,
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
                fontWeight: '500'
            },
            formatter: '{b}<br/>{c}'
        },
        geo: {
            map: mapName,
            roam: true,
            zoom: 1.3,
            center: [118.5, 24.5],
            itemStyle: {
                areaColor: 'rgba(76, 175, 80, 0.2)',
                borderColor: 'rgba(76, 175, 80, 0.6)',
                borderWidth: 1.5
            },
            emphasis: {
                areaColor: 'rgba(76, 175, 80, 0.4)',
                borderColor: 'rgba(76, 175, 80, 0.8)',
                borderWidth: 2
            }
        },
        series: [{
            type: 'effectScatter',
            coordinateSystem: 'geo',
            symbolSize: 10,
            showEffectOn: 'render',
            rippleEffect: {
                brushType: 'stroke'
            },
            hoverAnimation: true,
            itemStyle: {
                color: '#ffaa00'
            },
            emphasis: {
                itemStyle: {
                    color: '#b67600'
                }
            },
            zlevel: 1,
            data: data || []
        }]
    };

    return { ...defaultOption, ...customOption };
};

// 图表实例管理器
export class ChartManager {
    constructor() {
        this.charts = new Map();
        this.resizeHandler = this.handleResize.bind(this);
        window.addEventListener('resize', this.resizeHandler);
    }

    // 创建图表
    createChart(id, dom, option, theme = 'custom') {
        if (this.charts.has(id)) {
            this.disposeChart(id);
        }

        const chart = echarts.init(dom, theme);
        chart.setOption(option);
        this.charts.set(id, chart);

        return chart;
    }

    // 获取图表
    getChart(id) {
        return this.charts.get(id);
    }

    // 更新图表配置
    updateChart(id, option, notMerge = false) {
        const chart = this.charts.get(id);
        if (chart) {
            chart.setOption(option, notMerge);
        }
    }

    // 销毁图表
    disposeChart(id) {
        const chart = this.charts.get(id);
        if (chart) {
            chart.dispose();
            this.charts.delete(id);
        }
    }

    // 销毁所有图表
    disposeAll() {
        this.charts.forEach(chart => chart.dispose());
        this.charts.clear();
    }

    // 处理窗口大小变化
    handleResize() {
        this.charts.forEach(chart => {
            chart.resize();
        });
    }

    // 清理资源
    destroy() {
        this.disposeAll();
        window.removeEventListener('resize', this.resizeHandler);
    }
}

// 导出默认实例
export const chartManager = new ChartManager();